<template>
  <view>
    <u-navbar :title="formType === 'add' ? '添加店员' : '编辑店员'" title-size="36" height="50">
      <view class="slot-wrap" @click="goBack">
        <text>返回</text>
      </view>
    </u-navbar>

    <view class="form-content">
      <u-form :model="form" ref="uForm" label-position="top">
        <u-form-item label="姓名" prop="contactName" :required="true">
          <u-input
            v-model="form.contactName"
            placeholder="请输入姓名"
            :border="true"
            :clearable="true"
          >
          </u-input>
        </u-form-item>

        <u-form-item label="手机号" prop="contactMobile" :required="true">
          <u-input
            v-model="form.contactMobile"
            placeholder="请输入手机号"
            type="number"
            :border="true"
            :clearable="true"
          >
          </u-input>
        </u-form-item>

        <u-form-item label="角色" prop="roles" :required="true">
          <u-checkbox-group @change="roleChange">
            <u-checkbox
              v-for="role in roleOptions"
              v-model="role.checked"
              :key="role.value"
              :name="role.value"
            >
              {{ role.label }}
            </u-checkbox>
          </u-checkbox-group>
        </u-form-item>
      </u-form>

      <button class="form-btn" @click="submitForm" :loading="submitLoading">
        {{ formType === 'add' ? '添加' : '保存' }}
      </button>
    </view>
  </view>
</template>

<script>
import { ROLE_OPTIONS } from '@/store/staff-roles'

export default {
  data() {
    return {
      formType: 'add', // add 或 edit
      staffId: null,
      submitLoading: false,
      form: {
        id: '',
        contactName: '',
        contactMobile: '',
        roles: []
      },
      roleOptions: [],
      rules: {
        contactName: [
          {
            required: true,
            message: '请输入店员姓名',
            trigger: ['change', 'blur']
          }
        ],
        contactMobile: [
          {
            required: true,
            message: '请输入手机号',
            trigger: ['change', 'blur']
          },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号格式不正确',
            trigger: ['change', 'blur']
          }
        ],
        roles: [
          {
            validator: (rule, value, callback) => {
              return value && value.length > 0
            },
            message: '请选择角色',
            trigger: ['change']
          }
        ]
      }
    }
  },

  onLoad(options) {
    this.roleOptions = ROLE_OPTIONS
    this.roleOptions.forEach((it) => {
      it.checked = false
    })
    this.formType = options.type
    if (this.formType === 'edit') {
      this.staffId = options.id
      this.loadStaffDetail()
    }

    // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
    this.$nextTick(() => {
      this.$refs.uForm.setRules(this.rules)
    })
  },

  methods: {
    // 加载店员详情
    async loadStaffDetail() {
      if (!this.staffId) {
        this.$u.toast('店员信息获取失败')
        return
      }
      try {
        // 调用获取详情API（异步方式）
        const res = await this.$u.get('/app-api/shop/staff/get', {
          id: this.staffId
        })
        if (res.code === 0) {
          const data = res.data
          this.form.contactName = data.contactName
          this.form.contactMobile = data.contactMobile
          this.form.roles = data.roles || []
          this.roleOptions.forEach((it) => {
            it.checked = this.form.roles.includes(it.value)
          })
        }
      } catch (error) {
        console.error('加载店员详情失败:', error)
        this.$u.toast('店员信息获取出错')
      }
    },

    // 角色变化
    roleChange(e) {
      console.log('roleChange: ' + JSON.stringify(e))
      this.form.roles = e
    },
    // 提交表单
    submitForm() {
      this.$refs.uForm.validate((valid) => {
        if (valid) {
          this.performSubmit()
        } else {
          this.$u.toast('请检查输入信息')
          console.log(JSON.stringify(this.form))
        }
      })
    },
    async performSubmit() {
      this.submitLoading = true
      try {
        let res
        if (this.formType === 'add') {
          // 调用添加API
          res = await this.$u.post('/app-api/shop/staff/create', this.form)
        } else {
          // 调用编辑API
          this.form.id = this.staffId
          res = await this.$u.post('/app-api/shop/staff/update', this.form)
        }

        if (res.code === 0) {
          this.$refs.uForm.resetFields()
          this.roleOptions.forEach((it) => {
            it.checked = false
          })
          this.$u.toast(this.formType === 'add' ? '添加成功' : '编辑成功')

          // 返回上一页并刷新列表
          setTimeout(() => {
            uni.navigateBack()
          }, 1000)
        } else {
          this.$u.toast(res.msg || (this.formType === 'add' ? '添加失败' : '编辑失败'))
        }
      } catch (error) {
        this.$u.toast(this.formType === 'add' ? '添加失败' : '编辑失败')
      } finally {
        this.submitLoading = false
      }
    },

    // 返回上一页
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.form-content {
  margin-top: 20rpx;
  background-color: #fff;
  padding: 30rpx;
  border-radius: 10rpx;
}

.form-btn {
  position: fixed;
  bottom: 40rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 80%;
  height: 72rpx;
  line-height: 72rpx;
  background: #10a28f;
  border-radius: 36rpx;
  font-size: 30rpx;
  color: #ffffff;
  text-align: center;
}
</style>
